package com.myp.chariotmicro.model.config.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myp.chariotmicro.model.response.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Sentinel自定义异常处理器，返回JSON格式响应
 */
@Component
public class SentinelJsonExceptionHandler implements BlockExceptionHandler {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       String origin,
                       BlockException e) throws IOException {
        // 设置响应内容类型为JSON
        response.setContentType("application/json;charset=UTF-8");

        ApiResponse<String> result;

        // 根据不同的异常类型返回不同的提示信息
        if (e instanceof FlowException) {
            result = ApiResponse.error(429, "请求过于频繁，请稍后再试");
        } else if (e instanceof DegradeException) {
            result = ApiResponse.error(503, "服务暂时降级，请稍后再试");
        } else if (e instanceof ParamFlowException) {
            result = ApiResponse.error(429, "热点参数请求过于频繁，请稍后再试");
        } else if (e instanceof SystemBlockException) {
            result = ApiResponse.error(503, "系统负载过高，请稍后再试");
        } else if (e instanceof AuthorityException) {
            result = ApiResponse.error(403, "请求被拒绝，没有访问权限");
        } else {
            result = ApiResponse.error(403, "请求被拦截");
        }

        // 将响应对象转换为JSON并写入响应流
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}